﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NewsProgram.Models;

namespace NewsProgram.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            NewsRepository repository = new NewsRepository();
            var model = repository.getTop10News();
            return View(model);
        }

        public ActionResult About()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Edit(int? id)
        {

            if (id.HasValue)
            {
                int realID = id.Value;
                NewsRepository reposistory = new NewsRepository();
                NewsItem n = reposistory.getNewsByID(realID);
                if (n != null)
                {
                    return View(n);
                }
            }

            return View("NotFound");
        }




        [HttpPost]
        public ActionResult Edit(int id, NewsItem n)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    NewsRepository repository = new NewsRepository();

                    if (n != null)
                    {
                        UpdateModel(n);
                        repository.updateNews(n);
                        return RedirectToAction("Index");
                    }

                    else
                    {
                        return View("NotFound");
                    }
                }
                catch (Exception ex)
                {
                    return View(n);
                }
            }
            else
            {
                return View(n);
            }
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View(new NewsItem());
        }
        [HttpPost]
        public ActionResult Create(NewsItem n)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    UpdateModel(n);
                    NewsRepository repository = new NewsRepository();
                    repository.addNews(n);
                    return RedirectToAction("Index");
                 }
                catch(Exception ex)
                {
                    return View(n);
                }
            }
            else
            {
                return View(n);
            }
        }


    }
}
